package com.zhentao.aliyun;

import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.socket.*;

import java.io.IOException;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName: WebSocketHandlerTest
 * @Author: 振涛教育_Q
 * @Date: 2024/12/4 19:05
 */
@Component
@Slf4j
public class WebSocketHandlerTest implements WebSocketHandler {

    private StringRedisTemplate redisTemplate;
    private WebSocketSession session;
    private ScheduledExecutorService scheduler;
    // 关闭标识
    private boolean isManuallyClosed = false;

    public WebSocketHandlerTest(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        this.session = session;
        log.info("WebSocket执行了------------");
        // 启动定时任务定期向客户端发送消息
        startPeriodicMessageSending();
    }

    @Override
    public void handleMessage(WebSocketSession webSocketSession, WebSocketMessage<?> webSocketMessage) throws Exception {
        log.info("客户端发送消息拉！！！------------");
        if (webSocketMessage instanceof TextMessage) {
            TextMessage textMessage = (TextMessage) webSocketMessage;
            String message = textMessage.getPayload();
            log.info("Received message: " + message);
            // 处理客户端发送的消息
            // ...
        }
    }

    @Override
    public void handleTransportError(WebSocketSession webSocketSession, Throwable throwable) throws Exception {
        if (!isManuallyClosed) {
            log.info("WebSocket接受消息出现了异常---------------");
            if (webSocketSession.isOpen()) {
                webSocketSession.sendMessage(new TextMessage("Error occurred: " + throwable.getMessage()));
            } else {
                log.warn("Cannot send error message because the WebSocket session is not open.");
            }
        }
    }

    @Override
    public void afterConnectionClosed(WebSocketSession webSocketSession, CloseStatus closeStatus) throws Exception {
        if (!isManuallyClosed) {
            log.info("WebSocket已经关闭------------------");
            if (webSocketSession.isOpen()) {
                webSocketSession.sendMessage(new TextMessage("连接关闭。。。。。。"));
            } else {
                log.warn("Cannot send close message because the WebSocket session is not open.");
            }
        }
    }

    @Override
    public boolean supportsPartialMessages() {
        return false;
    }

    private void startPeriodicMessageSending() {
        // 使用ScheduledExecutorService每隔5秒向客户端发送一次消息
        scheduler = Executors.newSingleThreadScheduledExecutor();
        scheduler.scheduleAtFixedRate(() -> {
            if (session != null && session.isOpen()) {
                try {
                    // 向客户端发送周期性消息
                    String msg = redisTemplate.opsForValue().get(AliyunConstans.ALIYUN_SPEECH_REDIS);
                    if(!StringUtils.isEmpty(msg)){
                        TextMessage message = new TextMessage(msg);
                        session.sendMessage(message);
                        log.info("消息成功发送----------------");
                    }
                    log.info("尝试发送消息----------------");
                } catch (Exception e) {
                    log.error("发送消息失败", e);
                }
            }
        }, 0, 1200, TimeUnit.MILLISECONDS); // 初始延迟0秒，5秒间隔
    }

    // 关闭方法
    public void close() {
        isManuallyClosed = true;
        if (session!= null && session.isOpen()) {
            try {
                session.close();
                log.info("WebSocket手动关闭成功");
            } catch (IOException e) {
                log.error("手动关闭WebSocket时出现异常", e);
            }
        }
        if (scheduler!= null) {
            scheduler.shutdownNow();
        }
    }

}
